package com.zhipu.balance.ui.home.calculate.wheat

import android.os.Bundle
import android.text.TextUtils
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.SPUtils
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.sjl.scanner.UsbKeyboardAutoScan
import com.zhipu.balance.R
import com.zhipu.balance.databinding.ActivityWheatBinding
import com.zhipu.balance.listener.AddNumberOnClickListener
import com.zhipu.balance.listener.AddOnClickListener
import com.zhipu.balance.mobile.event.RecordWheat
import com.zhipu.balance.mobile.temporaryClass.UniqueInfoById
import com.zhipu.balance.pop.NumberPopup
import com.zhipu.balance.ui.BaseActivity
import com.zhipu.balance.ui.home.calculate.adapter.ProfitOrderAdapter
import com.zhipu.balance.ui.home.calculate.corn.CornActivity
import com.zhipu.balance.ui.home.calculate.dami.DaMiActivity
import com.zhipu.balance.ui.home.calculate.rapeseed.RapeseedActivity
import com.zhipu.balance.ui.home.calculate.rice.RiceActivity
import com.zhipu.balance.ui.home.calculate.soybean.SoybeanActivity
import com.zhipu.balance.ui.vm.home.calculate.wheat.WheatViewModel
import com.zhipu.balance.utils.InitializeUtils
import com.zhipu.balance.utils.request.InterfaceRequestUtils

/**
 * 小麦
 */
class WheatActivity: BaseActivity<ActivityWheatBinding>() {

    /**
     * VM
     */
    private var mWheatViewModel: WheatViewModel? = null

    /**
     * 类型
     */
    private var productCategoryText : String? = null

    /**
     * usb键盘模式扫码示例，无需EditText接收,推荐
     */
    private val usbKeyboardAutoScan: UsbKeyboardAutoScan = UsbKeyboardAutoScan()



    override fun initCreate() {
        super.initCreate()
        InitializeUtils.AppComponent()?.doInjectionMain(this)
        mWheatViewModel = ViewModelProvider(this, viewModelFactory)[WheatViewModel::class.java]
    }


    override fun initParam() {
        super.initParam()
        productCategoryText = intent.getStringExtra("ProductCategoryText");
        println(productCategoryText)
    }


    /**
     * 初始化根布局
     *
     * @return 布局layout的id
     */
    override fun initContentView(savedInstanceState: Bundle?): Int {
        return R.layout.activity_wheat
    }

    override fun initView() {
        super.initView()
        binding.viewModel = mWheatViewModel

        binding.rv.layoutManager = LinearLayoutManager(mContext)
        binding.rv.adapter = mWheatViewModel?.mWheatAdapter
    }




    override fun initViewObservable() {
        super.initViewObservable()
        /**
         * Fragment回调
         */
        mWheatViewModel?.mFragments?.observe(this, Observer{ t ->
            var mProfitOrderAdapter = ProfitOrderAdapter(supportFragmentManager,t!!)
            binding.NoScrollViewPager.adapter = mProfitOrderAdapter
        })
        /**
         * 位置
         */
        mWheatViewModel?.mPosition?.observe(this,Observer{
            binding.NoScrollViewPager.currentItem = it
        })
        binding.NoScrollViewPager.setNoScroll(true);
        /**
         * 扫描枪回调
         */
        usbKeyboardAutoScan.setOnScanListener {
            InterfaceRequestUtils.getUniqueInfoById(it,object : AddOnClickListener {
                override fun onSkipClicked(sKip: String?) {
                    if(!TextUtils.isEmpty(sKip)){
                        var mUniqueInfoById = GsonUtils.fromJson(sKip, UniqueInfoById::class.java)
                        if(null != mUniqueInfoById){
                            when(mUniqueInfoById.productCategoryText){
                                "稻谷" -> {
                                    //小麦
                                    var mBundle = Bundle()
                                    mBundle.putString("ProductCategoryText",mUniqueInfoById.productCategoryText)
                                    ActivityUtils.startActivity(RiceActivity::class.java,mBundle)
                                }
                                "小麦" -> {
                                    mWheatViewModel?.UpdatePage(it)
                                }
                                "玉米" -> {
                                    //玉米
                                    var mBundle = Bundle()
                                    mBundle.putString("ProductCategoryText",mUniqueInfoById.productCategoryText)
                                    ActivityUtils.startActivity(CornActivity::class.java,mBundle)
                                }
                                "大米" -> {
                                    //大米
                                    var mBundle = Bundle()
                                    mBundle.putString("ProductCategoryText",mUniqueInfoById.productCategoryText)
                                    ActivityUtils.startActivity(DaMiActivity::class.java,mBundle)
                                }
                                "大豆" -> {
                                    //大豆
                                    var mBundle = Bundle()
                                    mBundle.putString("ProductCategoryText",mUniqueInfoById.productCategoryText)
                                    ActivityUtils.startActivity(SoybeanActivity::class.java,mBundle)
                                }
                                "油菜籽" -> {
                                    //油菜籽
                                    var mBundle = Bundle()
                                    mBundle.putString("ProductCategoryText",mUniqueInfoById.productCategoryText)
                                    ActivityUtils.startActivity(RapeseedActivity::class.java,mBundle)
                                }
                                else -> {
                                    mWheatViewModel?.UpdatePage(it)
                                }
                            }
                        }
                    }else{
                        mWheatViewModel?.UpdatePage(it)
                    }
                }
            })
        }

        /**
         * 编号
         */
        binding.ETNumber.setOnEditorActionListener(object : TextView.OnEditorActionListener{
            override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
                when(actionId){
                    EditorInfo.IME_ACTION_DONE ->{
                        if(!TextUtils.isEmpty(mWheatViewModel?.mNumber?.get())) {
                            val mNumberPopup = NumberPopup("小麦", mWheatViewModel?.mNumber?.get(),object :
                                AddNumberOnClickListener {
                                override fun <T> onSkipClicked(position: Int, item: T) {
                                    var mRecordWheat = item as RecordWheat
                                    mWheatViewModel?.updatePage(mRecordWheat)
                                }
                            })
                            XPopup.Builder(ActivityUtils.getTopActivity())
                                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                                .autoOpenSoftInput(false)
                                .asCustom(mNumberPopup)
                                .show();
                        }
                    }
                }
                return false
            }
        })

        //细分
        mWheatViewModel?.mImperfectSubdivision?.observe(this, Observer {
            SPUtils.getInstance().put("ImperfectSubdivision", it)
            mWheatViewModel?.switchover(it)
        })
    }


    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
        val defaultEd = SPUtils.getInstance().getString("SerialNumber")
        if (defaultEd == "扫码枪") {
            if (usbKeyboardAutoScan.isIntercept && event!!.keyCode != KeyEvent.KEYCODE_BACK) { //不处理返回键
                usbKeyboardAutoScan.analysisKeyEvent(event)
                return true //防止输入框接收事件
            }
        }
        return super.dispatchKeyEvent(event)
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (ev!!.action == MotionEvent.ACTION_DOWN) {
            val v = currentFocus
            if (isShouldHideKeyboard(v, ev)) {
                //隐藏软键盘
                KeyboardUtils.hideSoftInput(binding.NoScrollViewPager)
            }
        }
        return super.dispatchTouchEvent(ev)
    }

}